﻿using System;
using System.Linq;
using System.Reflection;

namespace HeroldIT.Dnn.Modules
{
    /// <summary>
    /// Provides information about the installed DotNetNuke environment.
    /// </summary>
    public static class Environment
    {
        /// <summary>
        /// Gets the current DotNetNuke version.
        /// </summary>
        public static Version DotNetNukeVersion
        {
            get
            {
                return new Version(GetAssemblyVersion("DotNetNuke"));
            }
        }

        /// <summary>
        /// Gets whether the given <paramref name="assembly"/> is available.
        /// </summary>
        /// <param name="assembly">The name of the assembly to check for.</param>
        /// <returns><c>true</c> if the given <paramref name="assembly"/> is available, otherwise <c>false</c>.</returns>
        public static bool IsAssemblyAvailable(string assembly)
        {
            return null != GetAssemblyVersion(assembly);
        }

        /// <summary>
        /// Gets the version of the given <paramref name="assembly"/>
        /// </summary>
        /// <param name="assembly">The assembly from which to get the version.</param>
        /// <returns>A <see cref="String"/> containing the version of the given <paramref name="assembly"/>,
        /// <see cref="string.Empty"/> if no version info was found, or <c>null</c> if the assembly is not available.</returns>
        public static string GetAssemblyVersion(string assembly)
        {
            try
            {
                Assembly a = Assembly.Load(assembly);
                var attribute = a.GetCustomAttributes(typeof (AssemblyVersionAttribute), false).OfType<AssemblyVersionAttribute>().SingleOrDefault();
                if (null != attribute)
                {
                    return attribute.Version;
                }
                return a.GetName().Version.ToString(4);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Gets whether the JQuery UI integration module library is installed.
        /// </summary>
        /// <returns><c>true</c> if the JQuery UI integration module library is installed, otherwise <c>false</c>.</returns>
        public static bool IsJQueryUIAvailable()
        {
            return IsAssemblyAvailable("HeroldIT.Dnn.JQuery");
        }
    }
}
